﻿using Autofac;
using SqlSugar;
using Sunny.UI;
using WinformDevFramework.IServices.System;


namespace WinformDevFramework
{
    public partial class FrmCreateCode : Form
    {
        private ISysDataSourceServices _dataSourceServices;
        public FrmCreateCode(ISysDataSourceServices sysDataSourceServices)
        {
            _dataSourceServices = sysDataSourceServices;
            InitializeComponent();
        }

        private void FrmCreateCode_Load(object sender, EventArgs e)
        {
            //初始化数据库 下拉框
            comboBox1.DataSource = _dataSourceServices.Query();
            comboBox1.DisplayMember = "ConnectName";
            comboBox1.ValueMember = "ID";
            this.uiComboTreeViewTable.CheckBoxes = true;
            this.uiComboTreeViewTable.DropDownStyle = Sunny.UI.UIDropDownStyle.DropDownList;
            uiComboTreeViewTable.ShowClearButton = true;
            uiComboTreeViewTable.ShowSelectedAllCheckBox = true;
            uiComboTreeViewTable.TextChanged += UiComboTreeViewTable_TextChanged;
            dataGridViewTable.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.controlType.DataSource = new string[] { "TextBox", "NumericUpDown", "CheckBox", "DateTimePicker", };
            dataGridViewTable.SelectionChanged += dataGridViewTable_SelectionChanged;
            dataGridViewTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridViewTable.MultiSelect = false;
        }

        private void dataGridViewTable_SelectionChanged(object? sender, EventArgs e)
        {
            DataGridView d = (DataGridView)sender;
            if (d.SelectedRows.Count > 0)
            {
                var selectedRow = d.SelectedRows[0];
                var selectedCell = selectedRow.Cells[0];
                if (selectedRow.Index > -1 && !string.IsNullOrEmpty(selectedCell.Value.ToString()))
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (!((ControlInfo)row.DataBoundItem).tableName.Equals(selectedCell.Value.ToString()))
                        {
                            CurrencyManager cm = (CurrencyManager)BindingContext[dataGridView1.DataSource];
                            cm.SuspendBinding();
                            row.Visible = false;
                            cm.ResumeBinding();

                        }
                        else
                        {
                            row.Visible = true;

                        }
                    }
                }
            }

        }

        private void UiComboTreeViewTable_TextChanged(object? sender, EventArgs e)
        {
            var tables = uiComboTreeViewTable.Text.Split(";").ToList();
            if (tables.Any())
            {
                List<ControlInfo> list = new List<ControlInfo>();
                ISqlSugarClient dbClient = AppInfo.Container.Resolve<ISqlSugarClient>();
                foreach (var item in tables)
                {
                    string str = item.TrimStart().TrimEnd();
                    string sqlGetAllTables = @"SELECT 
                            dataBaseFieldName = convert(varchar(100), a.name),
                            tableName = convert(varchar(50), d.name),
                            dataBaseFieldType = CONVERT(varchar(50), b.name),
                            dataBaseFieldDDesr = convert(varchar(50), isnull(g.[value], ''))
                            FROM dbo.syscolumns a
                            left join dbo.systypes b on a.xusertype = b.xusertype
                            inner join dbo.sysobjects d on a.id = d.id and d.xtype = 'U' and d.name <> 'dtproperties'
                            left join dbo.syscomments e on a.cdefault = e.id
                            left join sys.extended_properties g on a.id = g.major_id and a.colid = g.minor_id
                            left join sys.extended_properties f on d.id = f.major_id and f.minor_id = 0 " + $"where d.name = '{str}'";

                    //string strsql2 = $"SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='{item}'";
                    //List<string> keysList = new List<string>();
                    //keysList.AddRange(dbClient.Ado.SqlQuery<string>(strsql2));

                    var data = dbClient.Ado.SqlQuery<ControlInfo>(sqlGetAllTables);
                    string strsql3 = $"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME='{str}' AND  COLUMNPROPERTY( OBJECT_ID('{str}'),COLUMN_NAME,'IsIdentity')=1";
                    List<string> IdentityList = new List<string>();
                    IdentityList.AddRange(dbClient.Ado.SqlQuery<string>(strsql3));

                    data.ForEach(p =>
                    {
                        p.controlName = p.dataBaseFieldName;
                        p.controlType = GetControlType(p.dataBaseFieldType);
                        p.isIdentity = IdentityList.Contains(p.dataBaseFieldName);
                        p.labelName = "lbl" + p.dataBaseFieldName;
                        p.labelText = p.dataBaseFieldDDesr;
                    });
                    list.AddRange(data);
                }
                dataGridView1.DataSource = list;
                dataGridViewTable.DataSource = list.Distinct(p => p.tableName).ToList();
                foreach (DataGridViewColumn column in dataGridViewTable.Columns)
                {
                    if (!column.Name.Equals("tableName"))
                    {
                        column.Visible = false;
                    }
                }
                dataGridView1.Columns["tableName"].Visible = false;
                dataGridView1.Columns["dataBaseFieldDDesr"].Visible = false;
            }

        }

        private string GetControlType(string dataType)
        {
            string type = "TextBox";
            switch (dataType)
            {
                case "int":
                    type = "NumericUpDown"; break;
                case "decimal":
                    type = "NumericUpDown"; break;
                case "bit":
                    type = "CheckBox"; break;
                case "datetime":
                    type = "DateTimePicker"; break;
            }

            return type;
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = comboBox1.SelectedValue.ToInt32();
            sysDataSource dataSource = _dataSourceServices.QueryById(id);
            if (dataSource is not null)
            {
                var connectionString =
    $"Server={dataSource.Host};Database={dataSource.DataBaseName};User Id = {dataSource.Username}; Password={dataSource.Password}";

                textBox1.Text = connectionString;
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBox1.Text))
            {
                MessageBox.Show("请选择数据库！");
                return;
            }
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = textBox1.Text
                ,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
            try
            {
                db.Open();
                string sqlGetAllTables = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES order by TABLE_NAME";
                var tables = db.Ado.SqlQuery<string>(sqlGetAllTables);
                uiComboTreeViewTable.TreeView.Nodes.Clear();
                foreach (var table in tables)
                {
                    uiComboTreeViewTable.Nodes.Add(table);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                var tables = uiComboTreeViewTable.Text.Split(';');
                List<string> ts = new List<string>();
                foreach (var table in tables)
                {
                    var t = table.TrimEnd().TrimStart();
                    if (!string.IsNullOrEmpty(t))
                        ts.Add(t);
                }
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = textBox1.Text
                    ,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });
                try
                {
                    //生成实体类
                    db.DbFirst.IsCreateAttribute().Where(p => ts.Contains(p)).CreateClassFile($"{txtUrl.Text}\\Entity", txtNameSpace.Text);
                    var isc = new IServicesCreate();
                    var sc = new ServicesCreate();
                    var irc = new IRepositoryCreate();
                    var rc = new RepositoryCreate();
                    var wc = new WinformCreate();
                    var data = dataGridView1.DataSource as List<ControlInfo>;
                    //生成Iservices Services  IRepository Repository
                    ts.ForEach(p =>
                    {
                        isc.Create(p, txtNameSpace.Text, txtUrl.Text);
                        sc.Create(p, txtNameSpace.Text, txtUrl.Text);
                        irc.Create(p, txtNameSpace.Text, txtUrl.Text);
                        rc.Create(p, txtNameSpace.Text, txtUrl.Text);
                        wc.Create(p, txtNameSpace.Text, txtUrl.Text, data.Where(x => x.tableName.Equals(p)).ToList());
                    });

                    MessageBox.Show("生成成功");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TabControl parentTabControl = this.Parent.Parent as TabControl;
            TabPage tabpage = this.Parent as TabPage;
            parentTabControl.TabPages.Remove(tabpage);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedPath = folderBrowserDialog.SelectedPath;
                    // 在这里可以使用选择的路径进行后续操作
                    txtUrl.Text = selectedPath;
                }
            }
        }

        private bool ValidateData()
        {
            if (string.IsNullOrEmpty(comboBox1.Text))
            {
                MessageBox.Show("请选择数据库");
                return false;
            }
            if (string.IsNullOrEmpty(uiComboTreeViewTable.Text))
            {
                MessageBox.Show("请选择数据表");
                return false;
            }
            if (string.IsNullOrEmpty(txtNameSpace.Text))
            {
                MessageBox.Show("命名空间不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(txtUrl.Text))
            {
                MessageBox.Show("请选择文件生成目录");
                return false;
            }
            return true;
        }
    }
}
